package cn.iocoder.yudao.module.jifenyuan.dal.redis;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static cn.iocoder.yudao.module.jifenyuan.dal.redis.RedisKeyConstants.JIFENYUAN_TEST_ADD_COIN;
@Repository
public class JifenyuanLockRedisDao {

        @Resource
        private RedissonClient redissonClient;

        public void lock(Long id, Long timeoutMillis, Runnable runnable) {
            String lockKey = formatKey(id);
            RLock lock = redissonClient.getLock(lockKey);
            try {
                lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
                // 执行逻辑
                runnable.run();
            } finally {
                lock.unlock();
            }
        }

        private static String formatKey(Long id) {
            return String.format(JIFENYUAN_TEST_ADD_COIN, id);
        }

    }
